#include <iostream>
#include <thread>
using namespace std;
using std::thread;
class singleton{
public:
    //怎么解决饿汉模式的线程安全问题呢
    //pthread_once库函数，把其第二个参数放入一个
    //特定的函数指针，使得在多线程的情况也只会被
    //执行一次
     static singleton* getInstance(){
        cout<<"getInstance"<<endl;
         pthread_once(&_once,init);
        return _ps;
    }
    singleton(const singleton& rhs)=delete;
    singleton& operator=(const singleton& rhs)=delete;

    
    class autorelease{
    public:
        ~autorelease(){
            cout<<"~autorelease"<<endl;
            if(_ps){
                delete  _ps;
                _ps=nullptr;
            }
        }
};
private:
static void init(){
    if(_ps==nullptr){
        _ps=new singleton();
    }
}
singleton(){
    cout<<"singleton"<<endl;
}
~singleton(){
    cout<<"~singleton"<<endl;
}
    static singleton* _ps;
    static autorelease _ar;
    static pthread_once_t _once;
};
singleton* singleton::_ps=new singleton();
singleton:: autorelease singleton ::_ar;
pthread_once_t singleton::_once=PTHREAD_ONCE_INIT;
void test2(void);
void test(){
    thread t1(test2);
    thread t2(test2);
    thread t3(test2);
    thread t4(test2);
    thread t5(test2);

    t1.join();
    t2.join();
    t3.join();
    t4.join();
    t5.join();
}
void test2(){
    singleton::getInstance();
    singleton::getInstance();
}
int main(int argc, char * argv[]){
    test();
    return 0;
}

